<template>
  <el-dialog
    title="平面图管理"
    v-model="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="floor-plan-manager">
      <!-- 楼层信息 -->
      <div class="floor-info">
        <h3>{{ floor?.name }} - {{ floor?.venue?.name || '未知场馆' }}</h3>
        <p v-if="floor?.description">{{ floor.description }}</p>
        <p class="venue-location" v-if="floor?.venue">
          <el-tag type="info" size="small">{{ floor.venue.city }}, {{ floor.venue.country }}</el-tag>
        </p>
      </div>

      <!-- 当前平面图 -->
      <div class="current-plan-section">
        <h4>当前平面图</h4>
        <div v-if="floor?.floorPlanUrl" class="current-plan">
          <el-image
            :src="floor.floorPlanUrl"
            fit="contain"
            style="width: 100%; max-height: 400px; border-radius: 8px; border: 1px solid #dcdfe6;"
            preview-teleported
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
              </div>
            </template>
          </el-image>
          <div class="plan-actions">
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteFloorPlan"
              :loading="deleteLoading"
            >
              删除平面图
            </el-button>
          </div>
        </div>
        <div v-else class="no-plan">
          <el-empty description="暂无平面图" />
        </div>
      </div>

      <!-- 上传新平面图 -->
      <div class="upload-section">
        <h4>上传新平面图</h4>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          accept="image/*"
          drag
          class="plan-upload"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过10MB
            </div>
          </template>
        </el-upload>

        <!-- 预览新上传的图片 -->
        <div v-if="newPlanPreview" class="new-plan-preview">
          <h5>预览新平面图</h5>
          <el-image
            :src="newPlanPreview"
            fit="contain"
            style="width: 100%; max-height: 300px; border-radius: 8px; border: 1px solid #409eff;"
          />
          <div class="preview-actions">
            <el-button
              type="primary"
              size="small"
              @click="handleUploadFloorPlan"
              :loading="uploadLoading"
            >
              确认上传
            </el-button>
            <el-button
              size="small"
              @click="handleCancelUpload"
            >
              取消
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { Picture, UploadFilled } from '@element-plus/icons-vue'
import { floorApi, type Floor } from '@/api/floor'

interface Props {
  visible: boolean
  floor: Floor | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const uploadRef = ref()
const uploadLoading = ref(false)
const deleteLoading = ref(false)
const newPlanFile = ref<File | null>(null)
const newPlanPreview = ref<string>('')

// 计算属性：对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
})

// 文件选择处理
const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return
  
  // 验证文件类型
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return
  }
  
  // 验证文件大小 (10MB)
  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过10MB')
    return
  }
  
  newPlanFile.value = file.raw
  newPlanPreview.value = URL.createObjectURL(file.raw)
}

// 取消上传
const handleCancelUpload = () => {
  newPlanFile.value = null
  if (newPlanPreview.value) {
    URL.revokeObjectURL(newPlanPreview.value)
    newPlanPreview.value = ''
  }
}

// 上传平面图
const handleUploadFloorPlan = async () => {
  if (!newPlanFile.value || !props.floor) return

  try {
    uploadLoading.value = true
    await floorApi.uploadFloorPlan(props.floor.id, newPlanFile.value)
    ElMessage.success('平面图上传成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 删除平面图
const handleDeleteFloorPlan = async () => {
  if (!props.floor?.floorPlanUrl) return

  try {
    await ElMessageBox.confirm(
      '确定要删除当前平面图吗？此操作不可恢复！',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    deleteLoading.value = true
    
    // 使用专门的删除平面图API
    await floorApi.deleteFloorPlan(props.floor.id)
    ElMessage.success('平面图删除成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  } finally {
    deleteLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  handleCancelUpload()
}
</script>

<style scoped lang="scss">
.floor-plan-manager {
  .floor-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 8px;
    
    h3 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 18px;
    }
    
    p {
      margin: 0 0 8px 0;
      color: #606266;
      font-size: 14px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .venue-location {
      margin-top: 8px;
    }
  }

  .current-plan-section,
  .upload-section {
    margin-bottom: 25px;
    
    h4 {
      margin: 0 0 15px 0;
      color: #303133;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .current-plan {
    .plan-actions {
      margin-top: 15px;
      text-align: center;
    }
  }

  .no-plan {
    padding: 40px 0;
    text-align: center;
  }

  .plan-upload {
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    background-color: #fafafa;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .el-icon--upload {
      font-size: 28px;
      color: #8c939d;
      margin-bottom: 10px;
    }

    .el-upload__text {
      color: #606266;
      font-size: 14px;
      
      em {
        color: #409eff;
        font-style: normal;
      }
    }

    .el-upload__tip {
      font-size: 12px;
      color: #909399;
      margin-top: 10px;
    }
  }

  .new-plan-preview {
    margin-top: 20px;
    padding: 20px;
    border: 1px solid #409eff;
    border-radius: 8px;
    background-color: #f0f9ff;
    
    h5 {
      margin: 0 0 15px 0;
      color: #409eff;
      font-size: 14px;
      font-weight: 500;
    }
    
    .preview-actions {
      margin-top: 15px;
      text-align: center;
      
      .el-button {
        margin: 0 5px;
      }
    }
  }

  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400px;
    background-color: #f5f7fa;
    border-radius: 8px;
    border: 1px dashed #dcdfe6;
    color: #909399;
    
    .el-icon {
      font-size: 48px;
      margin-bottom: 15px;
    }
    
    span {
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
